package com.suneee.trades.service.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.suneee.base.util.ContextHelper;
import com.suneee.base.util.JsonUtil;
import com.suneee.base.util.SueCloudDateUtil;
import com.suneee.base.util.Uuid16;
import com.suneee.channel.dao.ChannelDao;
import com.suneee.channel.entity.Channel;
import com.suneee.cloud.admin.dao.AdministratorDao;
import com.suneee.component.excel.ExcelUtil;
import com.suneee.context.page.Page;
import com.suneee.core.error.Assert;
import com.suneee.core.error.ErrorUtils;
import com.suneee.core.util.DateUtils;
import com.suneee.logistic.dao.EnterpriseLogisticDao;
import com.suneee.logistic.dao.LogisticDao;
import com.suneee.logistic.entity.EnterpriseLogistics;
import com.suneee.logistic.entity.Logistic;
import com.suneee.quartz.dao.ScheduleConfigDao;
import com.suneee.quartz.dao.ScheduleTimeDao;
import com.suneee.quartz.entity.ScheduleConfig;
import com.suneee.quartz.entity.TmallOrderEn;
import com.suneee.quartz.init.QuartzInit;
import com.suneee.refund.dao.RefundApplyDao;
import com.suneee.refund.entity.RefundApply;
import com.suneee.resources.ProductError;
import com.suneee.shop.dao.ShopDao;
import com.suneee.shop.entity.Shop;
import com.suneee.sso.admin.entity.Administrator;
import com.suneee.store.bean.SyncTmallResultBean;
import com.suneee.store.bean.ViewShopStockRecordsDTO;
import com.suneee.store.dao.ShopStockDao;
import com.suneee.store.entity.ShopStock;
import com.suneee.store.entity.StockDetail;
import com.suneee.store.entity.StockRecord;
import com.suneee.store.resources.StaticParam;
import com.suneee.store.service.IThirdPartyService;
import com.suneee.store.service.ProductService;
import com.suneee.store.service.ShopStockService;
import com.suneee.store.service.ThirdPartyFactory;
import com.suneee.trades.bean.OrderGoodsDTO;
import com.suneee.trades.bean.OrderInfoDTO;
import com.suneee.trades.bean.SendGoodsDTO;
import com.suneee.trades.bean.SendGoodsResult;
import com.suneee.trades.bean.SynLogDTO;
import com.suneee.trades.bean.TradesInfoDTO;
import com.suneee.trades.bean.TradesOrderDTO;
import com.suneee.trades.bean.TradesOrderMapDTO;
import com.suneee.trades.dao.HistoryOrderDao;
import com.suneee.trades.dao.OrderLogDao;
import com.suneee.trades.dao.PromotionDetailsDao;
import com.suneee.trades.dao.ShoppDao;
import com.suneee.trades.dao.ShoppDetailDao;
import com.suneee.trades.dao.SynLogDao;
import com.suneee.trades.dao.TradesInfoDao;
import com.suneee.trades.dao.TradesOrderDao;
import com.suneee.trades.dao.ViewShoppDao;
import com.suneee.trades.dao.ViewShoppDetailDao;
import com.suneee.trades.dao.ViewShoppDetailExportDao;
import com.suneee.trades.entity.HistoryOrder;
import com.suneee.trades.entity.OrderLog;
import com.suneee.trades.entity.PromotionDetails;
import com.suneee.trades.entity.ScheduleTime;
import com.suneee.trades.entity.Shopp;
import com.suneee.trades.entity.ShoppDetail;
import com.suneee.trades.entity.SynLog;
import com.suneee.trades.entity.TradesInfo;
import com.suneee.trades.entity.TradesOrder;
import com.suneee.trades.entity.ViewShopp;
import com.suneee.trades.entity.ViewShoppDetail;
import com.suneee.trades.entity.ViewShoppDetailExport;
import com.suneee.trades.init.TradesInfoInitialization;
import com.suneee.trades.resource.BusiType;
import com.suneee.trades.resource.MergeStatus;
import com.suneee.trades.resource.OfflineStatus;
import com.suneee.trades.resource.OrderStatus;
import com.suneee.trades.resource.ShoppStatus;
import com.suneee.trades.resource.ShoppType;
import com.suneee.trades.resource.SplitStatus;
import com.suneee.trades.resource.SynType;
import com.suneee.trades.resource.TradeType;
import com.suneee.trades.resource.TradesStatus;
import com.suneee.trades.service.TradesInfoService;
import com.suneee.web.bean.DownloadInfo;
import com.suneee.web.bean.UploadInfo;

@Service("api-tradesInfo")
public class TradesInfoServiceImpl implements TradesInfoService {

	private static final Logger logger = LoggerFactory.getLogger(TradesInfoServiceImpl.class);


	@Autowired
	public TradesInfoDao tradesInfoDao;
	
	@Autowired
	private RefundApplyDao refundApplyDao;

	@Autowired
	public ShoppDao shoppDao;

	@Autowired
	public ShoppDetailDao shoppDetailDao;

	@Autowired
	private ShopStockDao shopStockDao;

	@Autowired
	private ProductService productService;

	@Autowired
	public TradesOrderDao tradesOrderDao;

	@Autowired
	public OrderLogDao orderLogDao;

	@Autowired
	public PromotionDetailsDao promotionDetailsDao;

	@Autowired
	private ShopDao shopDao;

	@Autowired
	private ScheduleTimeDao scheduleTimeDao;

	@Autowired
	private SynLogDao synLogDao;
	
	@Autowired
	public ViewShoppDetailExportDao viewShoppDetailExportDao;
	
	@Autowired
	public ViewShoppDao viewShoppDao;
	
	@Autowired
	public ViewShoppDetailDao viewShoppDetailDao;
	
	@Autowired
	public LogisticDao logisticDao;

	@Autowired
	public AdministratorDao administratorDao;
	
	@Autowired
	private EnterpriseLogisticDao enterpriseLogisticDao;
	
	@Autowired
	private ShopStockService shopStockService;
	
	@Autowired
	private ScheduleConfigDao scheduleConfigDao;
	
	@Autowired
	private ChannelDao channelDao;
	
	@Autowired
	private HistoryOrderDao historyOrderDao;
	
	@Override
	@Transactional
	public TradesInfo getCanCombinedOrder(TradesInfoDTO dto) {
		String[] tids = dto.getTids();
		
		Integer adminId = ContextHelper.getCurrentLoginInfo().getAdminId();

		// 待合并订单中是否有订单被锁定，有则抛出异常，否则批量锁单
		boolean locked = tradesInfoDao.isLocked(tids,adminId);
		if (locked) {
			throw ErrorUtils.wrap(ProductError.TRADES_IS_LOCKED);
		}
		// 批量锁单
		updateLocked(tids, adminId, true);

		// 获取页面展示的交易信息
		TradesInfo tradesInfo = tradesInfoDao.select(tids[0]);
		if(null != tradesInfo.getCompanyCode()){
			Logistic logistic = logisticDao.select(tradesInfo.getCompanyCode());
			tradesInfo.setCompanyName(logistic.getCompanyName());
		}
		
		List<TradesOrderMapDTO> listDTO = new ArrayList<>();
		for (int i = 0; i < tids.length; i++) {
			String tid = tids[i];
			List<TradesOrder> tradesOrder = tradesOrderDao.getTradesOrderByTid(tid);
			List<PromotionDetails> promotionDetails = promotionDetailsDao.selectByTid(tid);
			List<String> promotionId = new ArrayList<>();
			List<String> promotionName = new ArrayList<>();
			for(int j = 0; j < promotionDetails.size(); j++){
				PromotionDetails detail = promotionDetails.get(j);
				promotionId.add(detail.getPromotionId());
				promotionName.add(detail.getPromotionName());
			}
			for(int j = 0; j < tradesOrder.size(); j++){
				TradesOrder order = tradesOrder.get(j);
				order.setPromotionId(StringUtils.join(promotionId,","));
				order.setPromotionName(StringUtils.join(promotionName,","));
				if(StringUtils.isNotEmpty(order.getPayment())){
					float payment = Float.valueOf(order.getPayment());
					Integer num = order.getNum();
					float sales = (float)payment/num;
					DecimalFormat df = new DecimalFormat("0.00");
					String format = df.format(sales);
					order.setSalePrice(format);
				}
			}
			TradesOrderMapDTO mapDTO = new TradesOrderMapDTO();
			mapDTO.setTid(tid);
			mapDTO.setList(tradesOrder);
			listDTO.add(mapDTO);
		}
		tradesInfo.setTradesOrderMap(listDTO);
		return tradesInfo;
	}

	// 更新锁单状态
	private void updateLocked(String[] tids, Integer locked, boolean isLocked) {
		List<Object> list = new ArrayList<>();
		Collections.addAll(list, tids);
		List<TradesInfo> TradesInfoList = tradesInfoDao.batchTradesInfoByTid(list);
		for (int i = 0; i < TradesInfoList.size(); i++) {
			TradesInfo tradesInfo = TradesInfoList.get(i);
			tradesInfo.setIs_Locked(isLocked);
			tradesInfo.setLocked(locked);
		}
		tradesInfoDao.batchUpdateTradesInfo(TradesInfoList);
	}

	@Override
	@Transactional
	public void combinedOrders(TradesInfoDTO dto) 
	{

		String[] tids = dto.getTids();
		for(String tid:tids)
		{
			if(tradesInfoDao.checkRefundId(tid))
			{
				throw ErrorUtils.wrap(ProductError.TRADES_REFUND_APPLY_ALREADY,dto.getTid()+":该销售单已经有售后单存在");
			}
		}

		Integer adminId = ContextHelper.getCurrentLoginInfo().getAdminId();

		List<String> comTid = Arrays.asList(tids); // 待合并的交易流水号

		TradesInfo tradesInfo = tradesInfoDao.getTradesInfo(tids[0]);
		String[] split = tradesInfo.getMergeTids().split(",");
		String companyCode = tradesInfo.getCompanyCode();

		List<Object> allTid = new ArrayList<>();// 所有可合并的交易流水号
		Collections.addAll(allTid, split);

		// 获取所有可合并的交易信息
		List<TradesInfo> tradesInfos = tradesInfoDao.batchTradesInfoByTid(allTid);

		String mergeTids = null;

		if (comTid.size() != allTid.size()) { // 只合并部分订单
			allTid.removeAll(comTid);
			mergeTids = StringUtils.join(allTid, ",");
		}
		List<OrderLog> orderLogs = new ArrayList<>(); // 订单处理日志

		for (int i = 0; i < tradesInfos.size(); i++) {
			TradesInfo tradesInfoTmp = tradesInfos.get(i);
			String tid = tradesInfoTmp.getTid();
			if (comTid.contains(tid)) {
				tradesInfoTmp.setMergeStatus(MergeStatus.ACHIEVE_MERGE.name());
				tradesInfoTmp.setMergeTids(null);
				tradesInfoTmp.setOfflineStatus(OfflineStatus.WAIT_SEND_GOODS.name());
				tradesInfoTmp.setAuditTime(DateUtils.getCurrentTimestamp());

				orderLogs.add(createOrderLog(tid, "1", adminId, BusiType.COMBINED_ORDERS.getValue(), "合并发货","合并成功","无"));
			} else {
				tradesInfoTmp.setMergeTids(mergeTids);
				if ("".equals(mergeTids)) {
					tradesInfoTmp.setMergeStatus("");
				}
			}
		}

		// 批量更新合单状态为已合并.可和单交易流水.客服处理状态
		tradesInfoDao.batchUpdateTradesInfo(tradesInfos);

		// 生成发货单
		Shopp shopp = createShopp(adminId, companyCode);

		// 生成发货明细
		List<TradesOrder> achieveOrders = tradesOrderDao.batchTradesOrderByTids(tids);
		createShoppDetail(achieveOrders, shopp.getShoppId());

		// 生成订单处理日志
		orderLogDao.insert(orderLogs);

		// 解锁订单
		updateLocked(tids, null, false);
	}
	
	@Override
	public Shopp createShopp(Integer createUserId, String companyCode) {
		Shopp shopp = new Shopp();
		shopp.setCompanyCode(companyCode);
		shopp.setCreateTime(DateUtils.getCurrentTimestamp());
		shopp.setCreateUserId(createUserId);
		shopp.setShoppType(ShoppType.ORDER_SEND_GOODS.name());
		shopp.setStatus(ShoppStatus.WAIT_SEND_GOODS.name());
		shoppDao.insert(shopp);
		return shopp;
	}

	@Override
	public void createShoppDetail(List<TradesOrder> achieveOrders, Integer shoppId) {
		List<ShoppDetail> shoppDetails = new ArrayList<>();
		for (int i = 0; i < achieveOrders.size(); i++) {
			TradesOrder TradesOrder = achieveOrders.get(i);
			ShoppDetail detail = new ShoppDetail();
			detail.setTid(TradesOrder.getTid());
			detail.setShoppId(shoppId);
			detail.setOrderId(TradesOrder.getOrderId());
			detail.setNum(TradesOrder.getNum());
			detail.setRefundId(TradesOrder.getRefundId());
			shoppDetails.add(detail);
		}
		shoppDetailDao.insert(shoppDetails);
	}

	@Override
	@Transactional
	public void splitOrders(TradesInfoDTO dto) {
		Assert.notNull(dto.getTid(), "订单号");
		String tid = dto.getTid();
		
		if(tradesInfoDao.checkRefundId(tid))
		{
			throw ErrorUtils.wrap(ProductError.TRADES_REFUND_APPLY_ALREADY,tid+":该销售单已经有售后单存在");
		}
		List<TradesOrderDTO> tradesOrderDTOs = dto.getTradesOrders();

		Integer adminId = ContextHelper.getCurrentLoginInfo().getAdminId();

		Integer totalNum = 0; // 总共购买数量
		Integer totalSplitNum = 0; // 已拆单数量+待拆单数量

		TradesInfo tradesInfo = tradesInfoDao.getTradesInfo(tid);

		List<TradesOrder> tradesOrders = tradesOrderDao.getTradesOrderByTid(tid);

		List<TradesOrder> splitTradesOrders = new ArrayList<>(); // 拆分商品

		for (int i = 0; i < tradesOrders.size(); i++) {
			TradesOrder tradesOrder = tradesOrders.get(i);
			Integer orderId = tradesOrder.getOrderId();
			totalNum = totalNum + tradesOrder.getNum();
			Integer splitNum = null == tradesOrder.getSplitNum() ? 0 : tradesOrder.getSplitNum();
			totalSplitNum = totalSplitNum + splitNum;

			for (int j = 0; j < tradesOrderDTOs.size(); j++) {
				TradesOrderDTO tradesOrderDTO = tradesOrderDTOs.get(j);
				Integer orderIdDTO = tradesOrderDTO.getOrderId();
				if (orderId.equals(orderIdDTO)) {
					Integer splitNumTmp = splitNum+ tradesOrderDTO.getQuantity();
					if(splitNumTmp > tradesOrder.getNum()){
						throw ErrorUtils.wrap(ProductError.CHECK_SPLIT_QUANTITY);
					}
					
					tradesOrder.setSplitNum(splitNumTmp);
					totalSplitNum = totalSplitNum + tradesOrderDTO.getQuantity();
					splitTradesOrders.add(tradesOrder);
				}
			}
		}

	
	   if (totalNum == totalSplitNum) { // 拆单数量等于购买数量
			// 拆单完成
			tradesInfo.setSplitStatus(SplitStatus.SPLIT_ACHIEVE.name());
			tradesInfo.setOfflineStatus(OfflineStatus.WAIT_SEND_GOODS.name());
		} else { // 拆单数量小于购买数量
			tradesInfo.setSplitStatus(SplitStatus.SPLIT_IN.name());
			tradesInfo.setOfflineStatus(OfflineStatus.REVIEW_ORDER.name());
		}
		tradesInfo.setAuditTime(DateUtils.getTimestamp(new Date()));
		tradesInfo.setRemark(dto.getRemark());
		// 更新交易流水
		tradesInfoDao.update(tradesInfo);
		
		// 更新商品
		tradesOrderDao.update(splitTradesOrders);

		// 生成发货单
		Shopp shopp = createShopp(adminId, tradesInfo.getCompanyCode());

		String[] tids = new String[1];
		tids[0] = tid;
		// 生成发货明细
		createShoppDetail(splitTradesOrders, shopp.getShoppId());

		// 生成订单处理日志
		orderLogDao.insert(createOrderLog(tid, "1", adminId, "拆单发货",BusiType.ORDER_DISPOSE.name(),"拆单成功","无"));

		// 解锁订单
		updateLocked(tids, null, false);
	}

	@Override
	public OrderLog createOrderLog(String tid, String isSuccess, Integer adminId, String opContent, String busiType,String result,String remark) {
		OrderLog log = new OrderLog();
		log.setTid(tid);
		log.setIsSuccess(isSuccess);
		log.setCreateUserId(adminId);
		log.setCreateTime(DateUtils.getCurrentTimestamp());
		log.setResult(result);
		log.setRemark(remark);
		log.setBusiType(busiType);
		log.setOpContent(opContent);
		return log;
	}
	
	
	@Override
	@Transactional
	public void createOrder(OrderInfoDTO dto) {
		if (null != dto) {
			Integer adminId = ContextHelper.getCurrentLoginInfo().getAdminId();

			String tid = Uuid16.create().toString();

			List<OrderGoodsDTO> orderGoodsDTOs = dto.getDtos();
			dto.setShopId(dto.getDtos().get(0).getShopId());
			Shop shop = shopDao.get(dto.getDtos().get(0).getShopId());
			dto.setShopName(shop.getName());
			

			List<ViewShopStockRecordsDTO> vssrList = new ArrayList<>();
			
			List<Integer> shopIds = new ArrayList<>();
			for (int i = 0; i < orderGoodsDTOs.size(); i++) {
				OrderGoodsDTO orderGoodsDTO = orderGoodsDTOs.get(i);
				if(null != shopIds && shopIds.size() > 0){
					if(!shopIds.contains(orderGoodsDTO.getShopId())){
						throw ErrorUtils.wrap(ProductError.CHECK_GOODS_SHOP);
					}
				}
				shopIds.add(orderGoodsDTO.getShopId());
				ViewShopStockRecordsDTO vssr = new ViewShopStockRecordsDTO();
				vssr.setShopId(orderGoodsDTO.getShopId());
				vssr.setSkuId(Integer.valueOf(orderGoodsDTO.getOuterSkuId()));
				vssr.setSpuId(Integer.valueOf(orderGoodsDTO.getOuterIid()));
				vssr.setIncoming(orderGoodsDTO.getNum());
				vssr.setPrice(Float.valueOf(orderGoodsDTO.getPrice()));
				vssr.setStockId(orderGoodsDTO.getStockId());
				vssrList.add(vssr);
			}

			double payment = 0;
			double totalFee = 0;
			List<TradesOrder> successList = new ArrayList<>();
			List<SyncTmallResultBean> decreaseShopStocks = shopStockService.decreaseShopStocks(vssrList,shop.getShopId(),dto.getRemark(),StaticParam.CREATE_ORDER_OUT);
			for(SyncTmallResultBean strb : decreaseShopStocks){
				if(strb.getStatus()){
					for(OrderGoodsDTO orderGoodsDTO : orderGoodsDTOs ){
						String outerSkuId = orderGoodsDTO.getOuterSkuId();
						String outerIid = orderGoodsDTO.getOuterIid();
						String title = strb.getTitle();
						if(title.equals(outerSkuId)){
							payment += Double.valueOf(orderGoodsDTO.getPrice()) * orderGoodsDTO.getNum();
							totalFee += Double.valueOf(orderGoodsDTO.getPrice()) * orderGoodsDTO.getNum();
							ShopStock shopStock = shopStockDao.getListBySkuSpu(Integer.valueOf(outerIid), 
									Integer.valueOf(outerSkuId),
									ContextHelper.getCurrentLoginInfo().getEnterpriseCode(),
									shop.getShopId());
							TradesOrder tradesOrder = createTradesOrder(orderGoodsDTO, shopStock.getChannelSpu(), shopStock.getChannelSku(), tid);
							successList.add(tradesOrder);
						}
					}
				}
			}
		
			
			if(null != successList && successList.size() > 0){   //商品扣减库存成功
				
				TradesInfo tradesInfo = createTradesInfo(dto, tid,payment,totalFee); // 创建交易流水
				
				tradesOrderDao.insert(successList); // 创建扣减库存成功的订单详情
				
				// 生成发货单
				Shopp shopp = createShopp(adminId, tradesInfo.getCompanyCode());
				
				// 生成发货明细
				String[] tids = new String[1];
				tids[0] = tradesInfo.getTid();
				List<TradesOrder> achieveOrders = tradesOrderDao.batchTradesOrderByTids(tids);
				createShoppDetail(achieveOrders, shopp.getShoppId());
			}else{
				throw ErrorUtils.wrap(ProductError.CREATE_ORDER_FAILED);
			}
		}

	}
	

	
	private TradesOrder createTradesOrder(OrderGoodsDTO dto,String numIid,String skuId,String tid) {
		TradesOrder tradesOrder = new TradesOrder();
		tradesOrder.setOuterIid(dto.getOuterIid());
		tradesOrder.setOid(tid);
		tradesOrder.setBuyerRate(false);
		tradesOrder.setSellerRate(false);
		tradesOrder.setCid(dto.getCid());
		tradesOrder.setSkuId(skuId);
		tradesOrder.setTid(tid);
		tradesOrder.setStatus(TradesStatus.WAIT_SELLER_SEND_GOODS.name());
		tradesOrder.setTitle(dto.getTitle());
		tradesOrder.setPrice(dto.getPrice());
		tradesOrder.setNumIid(numIid);
		tradesOrder.setNum(dto.getNum());
		tradesOrder.setTotalFee(String.valueOf(Float.valueOf(dto.getPrice())*dto.getNum()));
		tradesOrder.setPayment(String.valueOf(Float.valueOf(dto.getPrice())*dto.getNum()));
		tradesOrder.setSkuPropertiesName(dto.getSkuPropertiesName());
		tradesOrder.setModified(DateUtils.getCurrent());
		tradesOrder.setOuterSkuId(dto.getOuterSkuId());
		tradesOrder.setIsAfterSale(0);
		return tradesOrder;
	}
	
	private TradesInfo createTradesInfo(OrderInfoDTO dto,String tid,double payment,double totalFee){
		TradesInfo tradesInfo = new TradesInfo();
		tradesInfo.setTid(tid);
		tradesInfo.setShopId(dto.getShopId());
		tradesInfo.setEnterpriseCode(ContextHelper.getCurrentLoginInfo().getEnterpriseCode());
		tradesInfo.setSellerNick(dto.getShopName());
		tradesInfo.setBuyerNick(dto.getBuyerNick());
		tradesInfo.setTitle(dto.getTitle());
		tradesInfo.setType("fixed");
		tradesInfo.setShippingType("express");
		tradesInfo.setReceiverName(dto.getReceiverName());
		tradesInfo.setReceiverState(dto.getReceiverState());
		tradesInfo.setReceiverCity(dto.getReceiverCity());
		tradesInfo.setReceiverDistrict(dto.getReceiverDistrict());
		tradesInfo.setReceiverTown(dto.getReceiverTown());
		tradesInfo.setReceiverAddress(dto.getReceiverAddress());
		tradesInfo.setReceiverZip(dto.getReceiverZip());
		tradesInfo.setReceiverMobile(dto.getReceiverMobile());
		tradesInfo.setReceiverPhone(dto.getReceiverPhone());
		tradesInfo.setTotalFee(BigDecimal.valueOf(totalFee));
		tradesInfo.setPayment(BigDecimal.valueOf(payment));
		tradesInfo.setInvoiceKind(dto.getInvoiceKind());
		tradesInfo.setInvoiceName(dto.getInvoiceName());
		tradesInfo.setInvoiceType(dto.getInvoiceType());
		tradesInfo.setCreated(DateUtils.getCurrentTimestamp());
		tradesInfo.setPayTime(DateUtils.getCurrentTimestamp());
		tradesInfo.setModified(DateUtils.getCurrentTimestamp());
		tradesInfo.setStatus(TradesStatus.WAIT_SELLER_SEND_GOODS.name());
		if(StringUtils.isEmpty(dto.getRemark())){
			tradesInfo.setRemark("无备注");
		}else{
			tradesInfo.setRemark(dto.getRemark());
		}
		tradesInfo.setOfflineStatus(OfflineStatus.WAIT_SEND_GOODS.name());
		tradesInfo.setCompanyCode(dto.getCompanyCode());
		tradesInfo.setAuditTime(DateUtils.getCurrentTimestamp());
		tradesInfo.setTradeType(TradeType.SELF_BUILT_ORDER.name());
		tradesInfoDao.insert(tradesInfo);
		return tradesInfo;
	}

//	@Override
//	public Page<TradesInfo> historyOrders(TradesInfoDTO dto) {
//		if (null == dto) {
//			dto = new TradesInfoDTO();
//		}
//		String enterpriseCode = ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode();
//		dto.setEnterpriseCode(enterpriseCode);
//		Page<TradesInfo> historyOrders = tradesInfoDao.historyOrders(dto);
//		List<TradesInfo> items = historyOrders.getItems();
//		for (int i = items.size() - 1; i >= 0; i--) {
//			TradesInfo tradesInfo = items.get(i);
//			tradesInfo.setCreated(DateUtils.getTimestamp(tradesInfo.getCreated()));
//			tradesInfo.setTradesStatus(setStatus(tradesInfo, 1));
//			tradesInfo.setShoppTime(setShoppTime(tradesInfo));
//		}
//		return historyOrders;
//	}
	
	@Override
	public Page<Map<String, Object>> historyOrders(TradesInfoDTO dto) {
		if (null == dto) {
			dto = new TradesInfoDTO();
		}
		String enterpriseCode = ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode();
		dto.setEnterpriseCode(enterpriseCode);
		Page<Map<String, Object>> historyOrders = tradesInfoDao.historyOrders(dto);
		List<Map<String, Object>> items = historyOrders.getItems();
		for (int i = items.size() - 1; i >= 0; i--) {
//			TradesInfo tradesInfo = (TradesInfo) items.get(i);
			
			Map<String, Object> mp = items.get(i);
			System.out.println(mp.get("shopId"));
			
//			mp.put("created", DateUtils.getTimestamp(mp.get("created"));
			TradesInfo tradesInfo = new TradesInfo();
			String isChangeGoods = (String) mp.get("isChangeGoods");
			String isRefund = (String) mp.get("isRefund");
			String isRefundGoods = (String) mp.get("isRefundGoods");
			
			if(isChangeGoods != null && isChangeGoods.equals("1")){
				tradesInfo.setChangeGoods(true);
			}
			if(isRefund != null && isRefund.equals("1")){
				tradesInfo.setRefund(true);
			}
			if(isRefundGoods != null && isRefundGoods.equals("1")){
				tradesInfo.setRefundGoods(true);
			}
			tradesInfo.setStatus(mp.get("status").toString());
//			
			
			mp.put("tradesStatus", setStatus(tradesInfo, 1));
			mp.put("shoppTime", setShoppTime(tradesInfo));
			
//			tradesInfo.setCreated(DateUtils.getTimestamp(tradesInfo.getCreated()));
//			tradesInfo.setTradesStatus(setStatus(tradesInfo, 1));
//			tradesInfo.setShoppTime(setShoppTime(tradesInfo));
		}
		return historyOrders;
	}
	
	
	private String setStatus(TradesInfo tradesInfo,int type){
		List<String> status =new ArrayList<>();
		if(tradesInfo.isChangeGoods()){
			status.add(OrderStatus.CHANGE_GOODS.getValue());
		}
		if(tradesInfo.isRefund()){
			status.add(OrderStatus.REFUND.getValue());
		}
		if(tradesInfo.isRefundGoods()){
			status.add(OrderStatus.REFUND_GOODS.getValue());
		}
		String sts = tradesInfo.getStatus();
		if(TradesStatus.TRADE_BUYER_SIGNED.name().equals(sts) || TradesStatus.TRADE_FINISHED.name().equals(sts)){
			status.add(type == 1 ? OrderStatus.TRADE_BUYER_SIGNED.name() : OrderStatus.TRADE_BUYER_SIGNED.getValue());
		}
		return StringUtils.join(status,",");
	}
	
	private String setOrderStatus(HistoryOrder order,int type){
		List<String> status =new ArrayList<>();
		if(order.isChangeGoods()){
			status.add(OrderStatus.CHANGE_GOODS.getValue());
		}
		if(order.isRefund()){
			status.add(OrderStatus.REFUND.getValue());
		}
		if(order.isRefundGoods()){
			status.add(OrderStatus.REFUND_GOODS.getValue());
		}
		String sts = order.getStatus();
		if(TradesStatus.TRADE_BUYER_SIGNED.name().equals(sts) || TradesStatus.TRADE_FINISHED.name().equals(sts)){
			status.add(type == 1 ? OrderStatus.TRADE_BUYER_SIGNED.name() : OrderStatus.TRADE_BUYER_SIGNED.getValue());
		}
		return StringUtils.join(status,",");
	}
	
	private Timestamp setOrderShoppTime(HistoryOrder order){
		List<TradesOrder> tradesOrder = tradesOrderDao.getTradesOrderByTid(order.getTid());
		List<Date> dateList = new ArrayList<>();
		for(int j = 0; j < tradesOrder.size(); j++){
			if(null != tradesOrder.get(j).getConsignTime()){
				dateList.add(tradesOrder.get(j).getConsignTime());
			}
			
		}
		Collections.sort(dateList);
		if(null != dateList && dateList.size() > 0){
			if(null != dateList.get(0)){
				return DateUtils.getTimestamp(dateList.get(0));
			}
			return null;
		}
		return null;
	}
	
	private Timestamp setShoppTime(TradesInfo tradesInfo){
		List<TradesOrder> tradesOrder = tradesOrderDao.getTradesOrderByTid(tradesInfo.getTid());
		List<Date> dateList = new ArrayList<>();
		for(int j = 0; j < tradesOrder.size(); j++){
			if(null != tradesOrder.get(j).getConsignTime()){
				dateList.add(tradesOrder.get(j).getConsignTime());
			}
			
		}
		Collections.sort(dateList);
		if(null != dateList && dateList.size() > 0){
			if(null != dateList.get(0)){
				return DateUtils.getTimestamp(dateList.get(0));
			}
			return null;
		}
		return null;
	}

	public static final String EXPORT_XLS = "/templates/historyOrders.export.xls";

	@Override
	public DownloadInfo exportOrders(Integer payTimeSort, String tid, Integer shopId, String buyerNick,
			String tradeType, String payStartTime, String payEndTime, String shoppStartTime, String shoppEndTime) {
		TradesInfoDTO dto = new TradesInfoDTO();
		dto.setPayTimeSort(payTimeSort);
		dto.setTid(tid);
		dto.setShopId(shopId);
		dto.setBuyerNick(buyerNick);
		dto.setTradeType(tradeType);
		dto.setPayStartTime(payStartTime);
		dto.setPayEndTime(payEndTime);
		dto.setShoppStartTime(shoppStartTime);
		dto.setShoppEndTime(shoppEndTime);
		String enterpriseCode = ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode();
		dto.setEnterpriseCode(enterpriseCode);
//		List<TradesInfo> historyOrders = tradesInfoDao.exportHistoryOrders(dto);
		List<HistoryOrder> historyOrders = historyOrderDao.exportHistoryOrders(dto);
		for (int i = 0; i < historyOrders.size(); i++) {
//			TradesInfo tradesInfo = historyOrders.get(i);
//			tradesInfo.setCreated(DateUtils.getTimestamp(tradesInfo.getCreated()));
//			tradesInfo.setTradesStatus(setStatus(tradesInfo,2));
//			tradesInfo.setShoppTime(setShoppTime(tradesInfo));
//			
			HistoryOrder order = historyOrders.get(i);
			order.setCreated(DateUtils.getTimestamp(order.getCreated()));
			order.setTradesStatus(setOrderStatus(order,2));
			order.setShoppTime(setOrderShoppTime(order));
			
			Shop shop = shopDao.select(order.getShopId());
			if(shop != null){
				order.setShopName(shop.getName());
			}
		}
		DownloadInfo downloadInfo = ExcelUtil.writeExcle(EXPORT_XLS, historyOrders,ExcelUtil.replaceTimestamp("历史订单列表"));
		return downloadInfo;
	}

	@Override
	public Page<ViewShopp> selectWaitSendGoods(TradesInfoDTO dto) {
		if (null == dto) {
			dto = new TradesInfoDTO();
		}
		String enterpriseCode = ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode();
		dto.setEnterpriseCode(enterpriseCode);
		List<Object> listparam = new ArrayList<Object>();
		listparam.add(ShoppStatus.FAIL_SEND_GOODS);
		listparam.add(ShoppStatus.WAIT_SEND_GOODS);
		dto.setSendStatus(listparam);
		Page<ViewShopp> viewShopps = viewShoppDao.selectWaitSendGoods(dto);
		for (int i = 0; i < viewShopps.getItems().size(); i++) {
			ViewShopp viewShopp = viewShopps.getItems().get(i);
			Integer shoppId = viewShopp.getShoppId();
			String status = viewShopp.getStatus();
			String failTids = viewShopp.getFailTids();
			List<ViewShoppDetail> list = viewShoppDetailDao.batchShoppDetailByShoppId(shoppId,true,viewShopp.getTid());
			if(null != viewShopp.getAuditTime())
			{
				viewShopp.setAuditTime(DateUtils.getTimestamp(viewShopp.getAuditTime()));
			}
			if(ShoppStatus.FAIL_SEND_GOODS.name().equals(status)){
				if(StringUtils.isNotEmpty(failTids)){
					String[] split = failTids.split(",");
					List<String> filTidList = new ArrayList<>();
					Collections.addAll(filTidList, split);
					for(int j = 0; j < list.size(); j++){
						ViewShoppDetail viewShoppDetail = list.get(j);
						String tid = viewShoppDetail.getTid();
						if(!filTidList.contains(tid)){
							list.remove(j);
						}
					}
				}
			}
			if(null == list || list.size() == 0)
			{
				viewShopps.getItems().remove(i);
				i--;
				continue;
			}
			viewShopp.setShoppDetails(list);
		}
		System.out.println("size: "+viewShopps.getItems().size());
		return viewShopps;
	}

	@Override
	public Page<ViewShopp> selectSendGoods(TradesInfoDTO dto) {
		if (null == dto) {
			dto = new TradesInfoDTO();
		}
		String enterpriseCode = ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode();
		dto.setEnterpriseCode(enterpriseCode);
		List<Object> listparam = new ArrayList<Object>();
		listparam.add(ShoppStatus.ALREADY_SEND_GOODS);
		dto.setSendStatus(listparam);
		Page<ViewShopp> viewShopps = viewShoppDao.selectWaitSendGoods(dto);
		for (int i = 0; i < viewShopps.getItems().size(); i++) {
			ViewShopp viewShopp = viewShopps.getItems().get(i);
			Integer shoppId = viewShopp.getShoppId();
			String status = viewShopp.getStatus();
			String failTids = viewShopp.getFailTids();
			List<ViewShoppDetail> list = viewShoppDetailDao.batchShoppDetailByShoppId(shoppId,false,viewShopp.getTid());
			if(null != viewShopp.getAuditTime())
			{
				viewShopp.setAuditTime(DateUtils.getTimestamp(viewShopp.getAuditTime()));
			}
			if(ShoppStatus.FAIL_SEND_GOODS.name().equals(status)){
				if(StringUtils.isNotEmpty(failTids)){
					String[] split = failTids.split(",");
					List<String> filTidList = new ArrayList<>();
					Collections.addAll(filTidList, split);
					for(int j = 0; j < list.size(); j++){
						ViewShoppDetail viewShoppDetail = list.get(j);
						String tid = viewShoppDetail.getTid();
						if(!filTidList.contains(tid)){
							list.remove(j);
						}
					}
				}
			}
			if(null == list || list.size() == 0)
			{
				viewShopps.getItems().remove(i);
				i--;
				continue;
			}
			viewShopp.setShoppDetails(list);
		}
		return viewShopps;
	}
	
	/**
	 * 打单发货
	 * @param dto
	 * @return
	 */
	@Override
	@Transactional
	public SendGoodsResult sendGoods(TradesInfoDTO dto) 
	{
		List<SendGoodsDTO> sendGoods = dto.getSendGoods();
		Integer adminId = ContextHelper.getCurrentLoginInfo().getAdminId();
		
		SendGoodsResult sgr = new SendGoodsResult(); //返回结果

		Integer failNum = 0;
		Integer successNum = 0;
		StringBuffer failMessage= new StringBuffer();

		List<Shopp> shopps = new ArrayList<>();    //发货单集合
		List<OrderLog> orderLogs = new ArrayList<>();  //操作日志集合
		List<TradesOrder> orderList = new ArrayList<>();   //交易订单集合

		for (int i = 0; i < sendGoods.size(); i++) {
			try {
				SendGoodsDTO sendGood = sendGoods.get(i);
				Integer shoppId = sendGood.getShoppId();
				String outSid = sendGood.getOutSid();

				if (StringUtils.isEmpty(outSid)) {
					throw ErrorUtils.wrap(ProductError.CHECK_OUTSID);
				}

				Shopp shopp = shoppDao.select(shoppId);
				if (shopp == null) {
					continue;
				}
				List<String> tids = new ArrayList<>();
				if (ShoppStatus.FAIL_SEND_GOODS.name().equals(shopp.getStatus())) {
					String[] split = shopp.getFailTids().split(",");
					Collections.addAll(tids, split);
				} else {
					List<ShoppDetail> list = shoppDetailDao.batchShoppDetailByShoppId(shoppId);
					for (int j = 0; j < list.size(); j++) {
						ShoppDetail shoppDetail = list.get(j);
						String tid = shoppDetail.getTid();
						if (!tids.contains(tid)) {
							tids.add(tid);
						}
					}
				}

				List<String> failTids = new ArrayList<>(); // 失败交易流水号
				for (int j = 0; j < tids.size(); j++) {
					Map<String, String> bizParam = new HashMap<>();
					String tid = tids.get(j);
					
					if(tradesInfoDao.checkRefundId(tid))
					{
						throw ErrorUtils.wrap(ProductError.TRADES_REFUND_APPLY_ALREADY,tid+":该销售单已经有售后单存在");	
					}
					TradesInfo tradesInfo = tradesInfoDao.select(tid);
					String splitStatus = tradesInfo.getSplitStatus();
					bizParam.put("tid", tid);
					bizParam.put("companyCode", tradesInfo.getCompanyCode());
					bizParam.put("outSid", outSid);
					bizParam.put("shop_id", tradesInfo.getShopId().toString());
					List<TradesOrder> tradesOrders = tradesOrderDao.getTradesOrderByTid(tid);
				
					if (SplitStatus.SPLIT_ACHIEVE.name().equals(splitStatus) || SplitStatus.SPLIT_IN.name().equals(splitStatus)) { // 拆单
						bizParam.put("is_split", "1");
						String orderIds = shoppDetailDao.getOrderIdsByShopId(shoppId);
						String[] split = orderIds.split(",");
						String oids = tradesOrderDao.getOidsByOrderids(split);
						bizParam.put("subTid", oids);
						List<String> asList = Arrays.asList(split);
						for (int m = tradesOrders.size() - 1; m >= 0; m--) {
							String orderId = tradesOrders.get(m).getOrderId().toString();
							tradesOrders.get(m).setConsignTime(DateUtils.getCurrent());
							if (!asList.contains(orderId)) {
								tradesOrders.remove(m);
							}
						}
					}else{
						for (int m = tradesOrders.size() - 1; m >= 0; m--) {
							tradesOrders.get(m).setConsignTime(DateUtils.getCurrent());
						}
					}
					if(tradesInfo.isChangeGoods()){
						orderLogs.add(createOrderLog(tid, "1", adminId, "客服发货", BusiType.ORDER_SEND_GOODS.name(),"发货成功", "换货"));
						
						//更新售后状态
						List<RefundApply> refundApplys = refundApplyDao.getListByTid(tid);
						if(refundApplys != null && refundApplys.size() > 0){
							RefundApply refundApply = refundApplys.get(0);
							refundApply.setFeedbackStatus("SEND_GOODS");
							refundApplyDao.update(refundApply);
						}
						
						successNum++;
						TradesInfo info = tradesInfoDao.select(tid);
						info.setStatus(TradesStatus.WAIT_BUYER_CONFIRM_GOODS.name());
						info.setOfflineStatus(ShoppStatus.ALREADY_SEND_GOODS.name());
						tradesInfoDao.update(info);
						
					}else if (TradeType.SELF_BUILT_ORDER.name().equals(tradesInfo.getTradeType())) {
						orderLogs.add(createOrderLog(tid, "1", adminId, "客服发货", BusiType.ORDER_SEND_GOODS.name(),"发货成功", "无"));
						TradesInfo info = tradesInfoDao.select(tid);
						info.setStatus(TradesStatus.TRADE_FINISHED.name());
						tradesInfoDao.update(info);
						
						successNum++;
						
						orderList.addAll(tradesOrders);
					} else {
						// 调用天猫接口
						if (!commercePlatformOrderStatus(bizParam)) {
							failMessage.append("调用天猫接口异常");
							failTids.add(tid);
							failNum++;
							orderLogs.add(createOrderLog(tid, "1", adminId, "客服发货", BusiType.ORDER_SEND_GOODS.name(),"发货失败", "无"));
						} else {
							successNum++;
							orderLogs.add(createOrderLog(tid, "1", adminId, "客服发货", BusiType.ORDER_SEND_GOODS.name(),"发货成功", "无"));
							orderList.addAll(tradesOrders);
							
							TradesInfo info = tradesInfoDao.select(tid);
							info.setStatus(TradesStatus.WAIT_BUYER_CONFIRM_GOODS.name());
							//info.setOfflineStatus(ShoppStatus.ALREADY_SEND_GOODS.name());
							tradesInfoDao.update(info);
						}
					}
				}
				if (null != failTids && failTids.size() > 0) {
					Shopp updateShopp = shoppDao.select(shoppId);
					//updateShopp.setOutSid(outSid);
					updateShopp.setShoppTime(DateUtils.getCurrentTimestamp());
					updateShopp.setShoppUserId(adminId);
					updateShopp.setStatus(ShoppStatus.FAIL_SEND_GOODS.name());
					updateShopp.setFailTids(StringUtils.join(failTids, ","));
					shopps.add(updateShopp);
				} else {
					Shopp updateShopp = shoppDao.select(shoppId);
					updateShopp.setOutSid(outSid);
					updateShopp.setShoppTime(DateUtils.getCurrentTimestamp());
					updateShopp.setShoppUserId(adminId);
					updateShopp.setStatus(ShoppStatus.ALREADY_SEND_GOODS.name());
					shopps.add(updateShopp);
				}
			} catch (Exception e) {
				logger.error("【" + sendGoods.get(i).toString() + "】发货异常:" + e.getMessage());
				failNum++;
				failMessage.append("后台接口调用异常");
			}
		}
		// 更新交易订单发货时间
		if(null != orderList && orderList.size() > 0)
		{
			tradesOrderDao.update(orderList);
		}
		
		//针对换货流程
		for (SendGoodsDTO send:sendGoods) 
		{
			if(null != send)
			{
				tradesOrderDao.executeUpdate(" UPDATE t_trades_order SET is_after_sale = 1 WHERE order_id IN (SELECT order_id FROM t_shopp_detail WHERE shopp_id = ?) ", send.getShoppId());	
			}
		}
		
		
		// 更新发货单的发货时间 运单号 发货人等
		shoppDao.update(shopps);
		// 记录订单处理日志
		orderLogDao.insert(orderLogs);
		sgr.setFailMessage(failMessage.toString());
		sgr.setFail(failNum);
		sgr.setSuccess(successNum);
		return sgr;
	}

	private boolean commercePlatformOrderStatus(Map<String,String> param) {
		String shop_id = param.get("shop_id");
		Shop shop = shopDao.get(Integer.valueOf(shop_id));
		String channelCode = shop.getChannelCode();
		IThirdPartyService client = null;
		if (StaticParam.TMALL_CODE.equalsIgnoreCase(channelCode)) {
			client = ThirdPartyFactory.getTmallClient();
		}

		if (null == client) {
			logger.error("无效渠道编码");
			return false;
		}
		
		Map<String, String> publicParams = JsonUtil.parse(shop.getRuleInfo());
		publicParams.put("url", shop.getProxyURL());
		
		try{
			boolean status = client.updateOrderShoppStatus(publicParams, param);
			return status;
		}catch(Exception e){
			logger.error(e.getMessage());
		    return false;	
		}
		
	}

	public static final String EXPORT_WAIT_SEND_GOODS_XLS = "/templates/waitSendGoods.export.xls";

	@Override
	public DownloadInfo exportWaitSendGoods(String title,Integer shopId,String companyName,String buyerNick,String tid,String createStartTime,String createEndTime,String reviewStartTime,String reviewEndTime,Integer[] shoppId) {
		TradesInfoDTO dto = new TradesInfoDTO();
		dto.setTitle(title);
		dto.setShopId(shopId);
		dto.setCompanyName(companyName);
		dto.setBuyerNick(buyerNick);
		dto.setTid(tid);
		dto.setCreateStartTime(createStartTime);
		dto.setCreateEndTime(createEndTime);
		dto.setReviewStartTime(reviewStartTime);
		dto.setReviewEndTime(reviewEndTime);
		dto.setShoppId(shoppId);
		String enterpriseCode = ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode();
		dto.setEnterpriseCode(enterpriseCode);
		List<ViewShoppDetailExport> exportXls = viewShoppDetailExportDao.exportXls(dto);
		DownloadInfo downloadInfo = ExcelUtil.writeExcle(EXPORT_WAIT_SEND_GOODS_XLS, exportXls,ExcelUtil.replaceTimestamp("待发货列表"));
		return downloadInfo;
	}
	
	public static final String IMPORT_WAIT_SEND_GOODS_XML = "/templates/waitSendGodds_import.xml";
	
	@Override
	public SendGoodsResult importWaitSendGoods(UploadInfo info) {
		
		List<SendGoodsDTO> list = new ArrayList<SendGoodsDTO>();
		TradesInfoDTO dto = new TradesInfoDTO();
		ExcelUtil.readExcle(info, IMPORT_WAIT_SEND_GOODS_XML, list, false);
		dto.setSendGoods(list);
		SendGoodsResult sendGoods = this.sendGoods(dto);
		return sendGoods;
	}
	
	@Override
	public void unlockTrades(TradesInfoDTO dto) 
	{
		String[] tids = dto.getTids();
		for(String tid:tids)
		{
			if(StringUtils.isEmpty(tid))
			{
				continue;
			}
			if(tradesInfoDao.checkRefundId(tid))
			{
				throw ErrorUtils.wrap(ProductError.TRADES_REFUND_APPLY_ALREADY,tid+":该销售单已经有售后单存在");	
			}
		}
		Integer adminId = ContextHelper.getCurrentLoginInfo().getAdminId();
		boolean locked = tradesInfoDao.isLocked(tids,adminId);
		if (!locked) {
			updateLocked(tids, null, false);
		}

	}
	
	@Override
	@Transactional
	public SynLog manualSyncOrder(TmallOrderEn entity) throws Exception {
		if(entity == null)
			entity = new TmallOrderEn();
		SynLog synLog = new SynLog();
		Integer totalNum = 0;
		boolean isSuccess = false;
		String returnInfo = "同步完成，返回新订单信息！";
		try {
			//如果3个条件输入了，就同步输入的交易号数据
			if(!StringUtils.isEmpty(entity.gettId()) && entity.getShopId() != null && entity.getStartSynTime() != null && entity.getEndSynTime() != null){
				System.out.println("tid");
				Shop shopEn = shopDao.select(entity.getShopId());
				TmallOrderEn onEntity = TradesInfoInitialization.getOneTradesInfo(shopEn, entity);
				if(onEntity.getIsSuccess()){
					totalNum = 1;
					isSuccess = true;
					Long num = Long.valueOf(totalNum.longValue());
					// 更新交易相关信息
					this.updateTrade(onEntity, tradesOrderDao, tradesInfoDao, shopStockDao, productService, promotionDetailsDao,shopDao,channelDao);
					this.updateSynLog(shopEn.getShopId(), shopEn.getEnterpriseCode(), num, SynType.MANUAL_SYNCHRONIZATION.name(), ContextHelper.getCurrentLoginInfo().getAccount(), synLogDao,isSuccess);
				}else{
					returnInfo = "同步失败，天猫接口调用异常";
					Long num = 0L;
					isSuccess = false;
					this.updateSynLog(shopEn.getShopId(), shopEn.getEnterpriseCode(), num, SynType.MANUAL_SYNCHRONIZATION.name(), ContextHelper.getCurrentLoginInfo().getAccount(), synLogDao,isSuccess);
				}
			}else if(!StringUtils.isEmpty(entity.gettId()) && entity.getShopId() != null) {
				//查询交易号对应的店铺数据
				System.out.println("tid+shopId");
				Shop shopEn = shopDao.select(entity.getShopId());
				TmallOrderEn onEntity = TradesInfoInitialization.getOneTradesInfo(shopEn, entity);
				if(onEntity.getIsSuccess()){
					totalNum = 1;
					isSuccess = true;
					Long num = Long.valueOf(totalNum.longValue());
					this.updateTrade(onEntity, tradesOrderDao, tradesInfoDao, shopStockDao, productService, promotionDetailsDao,shopDao,channelDao);
					this.updateSynLog(shopEn.getShopId(), shopEn.getEnterpriseCode(), num, SynType.MANUAL_SYNCHRONIZATION.name(), ContextHelper.getCurrentLoginInfo().getAccount(), synLogDao,isSuccess);
				}else{
					returnInfo = "同步失败，天猫接口调用异常";
					Long num = 0L;
					isSuccess = false;
					this.updateSynLog(shopEn.getShopId(), shopEn.getEnterpriseCode(), num, SynType.MANUAL_SYNCHRONIZATION.name(), ContextHelper.getCurrentLoginInfo().getAccount(), synLogDao,isSuccess);
				}
			}else if(!StringUtils.isEmpty(entity.gettId())){
				//根据交易号查找企业下所有店铺的数据
				System.out.println("tid+AllShopId");
				List<Shop> shopList = shopDao.selectWhere(" status='"+Shop.USE+"' and enabled = 1 and enterprise_code=?", ContextHelper.getCurrentLoginInfo().getEnterpriseCode());
				TmallOrderEn onEntity = null;
				if(shopList != null){
					for (Shop shop : shopList) {
						Shop shopEn = shopDao.select(shop.getShopId());
						TmallOrderEn curEntity = TradesInfoInitialization.getOneTradesInfo(shopEn, entity);
						if(curEntity.getIsSuccess()){
							onEntity = curEntity;
							isSuccess = true;
							this.updateTrade(onEntity, tradesOrderDao, tradesInfoDao, shopStockDao, productService, promotionDetailsDao,shopDao,channelDao);
							this.updateSynLog(shopEn.getShopId(), shopEn.getEnterpriseCode(), onEntity.getTotalRows(), SynType.MANUAL_SYNCHRONIZATION.name(), ContextHelper.getCurrentLoginInfo().getAccount(), synLogDao,isSuccess);
						}else{
							isSuccess = false;
							this.updateSynLog(shopEn.getShopId(), shopEn.getEnterpriseCode(), curEntity.getTotalRows(), SynType.MANUAL_SYNCHRONIZATION.name(), ContextHelper.getCurrentLoginInfo().getAccount(), synLogDao,isSuccess);
						}
					}
				}
				if(onEntity != null){
					totalNum = 1;
					isSuccess = true;
				}else{
					returnInfo = "同步失败，天猫接口调用异常";
					isSuccess = false;
				}
			}else if(entity.getStartSynTime() != null && entity.getEndSynTime() != null && entity.getShopId() != null){
				//如果输入了时间，选择了店铺，同步当前时间当前店铺交易
				System.out.println("time+ShopId");
				Shop shopEn = shopDao.select(entity.getShopId());
				Map<String, String> shopMap = JsonUtil.parse(shopEn.getRuleInfo());
				shopMap.put("proxUrl", shopEn.getProxyURL());
				
				TmallOrderEn odEntity = QuartzInit.synAllShopOrder(entity.getStartSynTime(),entity.getEndSynTime(),shopEn.getShopId(), shopEn.getEnterpriseCode(),"order", scheduleTimeDao, shopMap, shopStockDao,tradesInfoDao);
				
				this.updateTrade(odEntity, tradesOrderDao, tradesInfoDao, shopStockDao, productService, promotionDetailsDao,shopDao,channelDao);

				if(odEntity.getTotalRows() != null)
					totalNum += Integer.parseInt(odEntity.getTotalRows().toString());
				isSuccess = odEntity.getIsSuccess();
				if(!isSuccess){
					returnInfo = "同步失败，天猫接口查询异常";
				}
				this.updateSynLog(shopEn.getShopId(), shopEn.getEnterpriseCode(), odEntity.getTotalRows(), SynType.MANUAL_SYNCHRONIZATION.name(), ContextHelper.getCurrentLoginInfo().getAccount(), synLogDao,isSuccess);
			}else if(entity.getShopId() != null){
				//如果只选店铺，就查询店铺最后更新时间范围记录
				Shop shopEn = shopDao.select(entity.getShopId());
				Map<String, String> shopMap = JsonUtil.parse(shopEn.getRuleInfo());
				shopMap.put("proxUrl", shopEn.getProxyURL());
				
				TmallOrderEn odEntity = QuartzInit.synAllShopOrder(entity.getStartSynTime(),entity.getEndSynTime(),shopEn.getShopId(), shopEn.getEnterpriseCode(),"order", scheduleTimeDao, shopMap, shopStockDao,tradesInfoDao);
				this.updateTrade(odEntity, tradesOrderDao, tradesInfoDao, shopStockDao, productService, promotionDetailsDao,shopDao,channelDao);
				if(odEntity.getTotalRows() != null)
					totalNum += Integer.parseInt(odEntity.getTotalRows().toString());
				isSuccess = odEntity.getIsSuccess();
				if(!isSuccess){
					returnInfo = "同步失败，天猫接口调用异常";
				}
				this.updateSynLog(shopEn.getShopId(), shopEn.getEnterpriseCode(), odEntity.getTotalRows(), SynType.MANUAL_SYNCHRONIZATION.name(), ContextHelper.getCurrentLoginInfo().getAccount(), synLogDao,isSuccess);
			}else if(entity.getStartSynTime() != null && entity.getEndSynTime() != null){
				//同步选择的时间范围的所有店铺数据
				System.out.println("time+AllShopId");
				List<Shop> shopList = shopDao.selectWhere(" status='"+Shop.USE+"' and enabled = 1 and enterprise_code=?", ContextHelper.getCurrentLoginInfo().getEnterpriseCode());
				if(shopList != null){
					for (Shop shopEn : shopList) {
						Map<String, String> shopMap = JsonUtil.parse(shopEn.getRuleInfo());
						shopMap.put("proxUrl", shopEn.getProxyURL());
						TmallOrderEn odEntity = QuartzInit.synAllShopOrder(entity.getStartSynTime(),entity.getEndSynTime(),shopEn.getShopId(), shopEn.getEnterpriseCode(),"order", scheduleTimeDao, shopMap, shopStockDao,tradesInfoDao);
						this.updateTrade(odEntity, tradesOrderDao, tradesInfoDao, shopStockDao, productService, promotionDetailsDao,shopDao,channelDao);
						if(odEntity.getTotalRows() != null)
							totalNum += Integer.parseInt(odEntity.getTotalRows().toString());
						isSuccess = odEntity.getIsSuccess();
						this.updateSynLog(shopEn.getShopId(), shopEn.getEnterpriseCode(), odEntity.getTotalRows(), SynType.MANUAL_SYNCHRONIZATION.name(), ContextHelper.getCurrentLoginInfo().getAccount(), synLogDao,isSuccess);
					}
					if(!isSuccess){
						returnInfo = "同步失败，天猫接口查询异常";
					}
				}
			}else {
				//没有选，就同步所有所有店铺的
				System.out.println("AllShopId");
				List<Shop> shopList = shopDao.selectWhere(" status='"+Shop.USE+"' and enabled = 1 and enterprise_code=?", ContextHelper.getCurrentLoginInfo().getEnterpriseCode());
				if(shopList != null){
					for (Shop shopEn : shopList) {
						Map<String, String> shopMap = JsonUtil.parse(shopEn.getRuleInfo());
						shopMap.put("proxUrl", shopEn.getProxyURL());
						TmallOrderEn odEntity = QuartzInit.synAllShopOrder(null,null,shopEn.getShopId(), shopEn.getEnterpriseCode(),"order", scheduleTimeDao, shopMap, shopStockDao,tradesInfoDao);
						this.updateTrade(odEntity, tradesOrderDao, tradesInfoDao, shopStockDao, productService, promotionDetailsDao,shopDao,channelDao);
						if(odEntity.getTotalRows() != null)
							totalNum += Integer.parseInt(odEntity.getTotalRows().toString());
						isSuccess = odEntity.getIsSuccess();
						this.updateSynLog(shopEn.getShopId(), shopEn.getEnterpriseCode(), odEntity.getTotalRows(), SynType.MANUAL_SYNCHRONIZATION.name(), ContextHelper.getCurrentLoginInfo().getAccount(), synLogDao,isSuccess);
					}
					if(!isSuccess){
						returnInfo = "同步失败，天猫接口查询异常";
					}
				}
			}
			// 返回同步信息到前端
			synLog.setNum(totalNum);
			synLog.setIsSuccess(isSuccess);
			synLog.setReturnInfo(returnInfo);
		} catch (Exception e) {
			synLog.setIsSuccess(false);
			returnInfo = "同步失败！调用TMALL接口异常";
			logger.error("同步订单出错,错误信息：" + e.getMessage(), e);
		}
		return synLog;
	}
	
	@SuppressWarnings("unused")
	private ScheduleConfig getConfigEn(Shop shop){
		ScheduleConfig dto = new ScheduleConfig();
		dto.setShopId(shop.getShopId());
		ScheduleConfig config = scheduleConfigDao.getScheduleConfig(dto);
		if(config == null){
			//再根据企业编码查询配置信息
			dto.setShopId(null);
			dto.setEnterpriseCode(shop.getEnterpriseCode());
			config = scheduleConfigDao.getScheduleConfig(dto);
			//最后查询平台配置信息
			if(config == null){
				dto.setEnterpriseCode("suneee");
				config = scheduleConfigDao.getScheduleConfig(dto);
			}
		}
		return config;
	}

	@Override
	public Page<Map<String, Object>> examinList(TradesInfoDTO dto) {
		if(dto == null)
			dto = new TradesInfoDTO();
		dto.setEnterpriseCode(ContextHelper.getCurrentLoginInfo().getEnterpriseCode());
		return tradesInfoDao.getExaminPageList(dto);
	}
	
	@Override
	public TradesInfo orderDetial(String tid) {
		Assert.notEmpty(tid, "tid");
		TradesInfo info = new TradesInfo();
		info = tradesInfoDao.getTradesInfo(tid);
		if(info != null){
			List<TradesOrder> orderListd = tradesOrderDao.getTradesOrderByTid(tid);
			List<TradesOrder> orderList = new ArrayList<TradesOrder>();
			if(orderListd != null){
				for (TradesOrder tradesOrder : orderListd) {
					if(!com.suneee.core.util.StringUtils.isEmpty(tradesOrder.getPayment()) && tradesOrder.getNum() != null){
						Float price = Float.parseFloat(tradesOrder.getPayment()) / tradesOrder.getNum();
						tradesOrder.setSalePrice(price.toString());
						orderList.add(tradesOrder);
					}
				}
			}
			info.setTradesOrderList(orderList);
			
			Shop shop = shopDao.get(Integer.valueOf(info.getShopId()));
			if(shop != null)
				info.setChannelCode(shop.getChannelCode());
			Channel channel = channelDao.getChannelByChannelCode(shop.getChannelCode());
			if(channel != null)
				info.setChannelName(channel.getName());
			List<PromotionDetails> promotionList = promotionDetailsDao.selectByTid(tid);
			info.setPromotionList(promotionList);
			List<OrderLog> orderLogListd = orderLogDao.selectByTid(tid);
			List<OrderLog> orderLogList = new ArrayList<OrderLog>();
			if(orderLogListd != null){
				for (OrderLog orderLog : orderLogListd) {
					Administrator admin = administratorDao.select(orderLog.getCreateUserId());
					if(admin != null)
					{
						orderLog.setCreateUser(admin.getName());
					}
					orderLogList.add(orderLog);
				}
			}
			info.setOrderLogList(orderLogList);
			
			if(info.getCompanyCode() != null){
				Logistic logc = logisticDao.select(info.getCompanyCode());
				if(null != logc)
				{
					info.setCompanyName(logc.getCompanyName());	
				}
			}
//			info.setTradesStatus(setStatus(info, 1)); //售后状态
		   
		}
		return info;
	}
	
	@Override
	@Transactional
	public void submitOrder(TradesInfo info) {
		Assert.notEmpty(info.getTid(), "交易订单号");
		if(tradesInfoDao.checkRefundId(info.getTid()))
		{
			throw ErrorUtils.wrap(ProductError.TRADES_REFUND_APPLY_ALREADY,info.getTid()+":该销售单已经有售后单存在");
		}
		TradesInfo tradesInfo = tradesInfoDao.select(info.getTid());
		tradesInfo.setOfflineStatus(OfflineStatus.WAIT_SEND_GOODS.name());
		
		if(!com.suneee.core.util.StringUtils.isEmpty(info.getRemark()))
			tradesInfo.setRemark(info.getRemark());
		tradesInfoDao.update(tradesInfo);
		
		//筛选掉已拆单的商品
		List<TradesOrder> tradesOrderList= tradesOrderDao.getTradesOrderNotSpByTid(tradesInfo.getTid());
		
		//生成发货单
		Shopp shopp = createShopp(ContextHelper.getCurrentLoginInfo().getAdminId(), tradesInfo.getCompanyCode());
		createShoppDetail(tradesOrderList, shopp.getShoppId());//生成发货单明细
		
		
		//生成订单处理日志
		OrderLog  orderLog = new OrderLog();
		orderLog.setTid(tradesInfo.getTid());
		orderLog.setBusiType(BusiType.ORDER_DISPOSE.name());
		orderLog.setOpContent("客服修改订单状态,提交发货");
		orderLog.setIsSuccess("1");
		orderLog.setResult("处理成功");
		orderLog.setRemark("无");
		orderLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
		orderLog.setCreateUserId(ContextHelper.getCurrentLoginInfo().getAdminId());
		orderLogDao.insert(orderLog);
	}

	@Override
	@Transactional
	public void modifyOrder(TradesInfoDTO dto) {
		
		Assert.notEmpty(dto.getTid(), "交易订单号");
		//生成订单处理日志
		OrderLog  orderLog = new OrderLog();
		TradesInfo tradesInfo = tradesInfoDao.select(dto.getTid());
		if(!com.suneee.core.util.StringUtils.isEmpty(dto.getOfflineStatus())){
			if(dto.getOfflineStatus().equals("延迟发货")){
				orderLog.setOpContent(OfflineStatus.DELAYED_DELIVERY.getValue());
				tradesInfo.setOfflineStatus(OfflineStatus.DELAYED_DELIVERY.name());
			}
			if(dto.getOfflineStatus().equals("重新理单")){
				orderLog.setOpContent(OfflineStatus.RE_ORDER.getValue());
				tradesInfo.setOfflineStatus(OfflineStatus.RE_ORDER.name());
			}
			tradesInfoDao.update(tradesInfo);
		}
		if(dto.getIsLocked() != null){
			orderLog.setOpContent(OfflineStatus.ORDER_UNLOCK.getValue());
			tradesInfo.setLocked(dto.getIsLocked() ? 1 : 0);
			tradesInfoDao.update(tradesInfo);
		}
		
		if(dto.getRemark() != null){
			tradesInfo.setRemark(dto.getRemark());
			tradesInfoDao.update(tradesInfo);
		}
		
		if(dto.getMergeStatus() != null){
			orderLog.setOpContent(MergeStatus.ABANDON_MERGES.getValue());//放弃合并
			String [] merageTids = tradesInfo.getMergeTids().split(",");
			//更新关联的可合单
			for (int i = 0; i < merageTids.length; i++) {
				String tid = merageTids[i];
				TradesInfo entity = tradesInfoDao.select(tid);
				entity.setMergeStatus(MergeStatus.ABANDON_MERGE.name());
				entity.setMergeTids("");
				tradesInfoDao.update(entity);
			}
		}
		
		orderLog.setTid(tradesInfo.getTid());
		orderLog.setBusiType(BusiType.ORDER_DISPOSE.name());
		orderLog.setIsSuccess("1");
		orderLog.setResult("处理成功");
		orderLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
		orderLog.setCreateUserId(ContextHelper.getCurrentLoginInfo().getAdminId());
		orderLogDao.insert(orderLog);
		
	}
	
	@Override
	public TradesInfo modifyLogistics(TradesInfoDTO dto) {
		
		Assert.notEmpty(dto.getTid(), "交易订单号");
		TradesInfo tradesInfo = tradesInfoDao.select(dto.getTid());
		
		tradesInfo.setReceiverState(dto.getReceiverState());
		tradesInfo.setReceiverCity(dto.getReceiverCity());
		tradesInfo.setReceiverDistrict(dto.getReceiverDistrict());
		tradesInfo.setReceiverAddress(dto.getReceiverAddress());
		tradesInfo.setReceiverName(dto.getReceiverName());
		tradesInfo.setReceiverZip(dto.getReceiverZip());
		tradesInfo.setReceiverMobile(dto.getReceiverMobile());
		tradesInfo.setReceiverPhone(dto.getReceiverPhone());
		tradesInfo.setCompanyCode(dto.getCompanyCode());
		if(tradesInfo.getCompanyCode() != null){
			Logistic logc = logisticDao.select(tradesInfo.getCompanyCode());
			tradesInfo.setCompanyName(logc.getCompanyName());
		}
		tradesInfoDao.update(tradesInfo);
		
		return tradesInfo;
		
	}

	@Override
	public Page<Map<String, Object>> synchronizeOrderInfo(SynLogDTO dto) {
		if(dto == null)
			dto = new SynLogDTO();
		dto.setEnterpriseCode(ContextHelper.getCurrentLoginInfo().getEnterpriseCode());
		return synLogDao.synchronizeOrderInfo(dto);
	}

	@Override
	@Transactional
	public void updateSynLogTable(TmallOrderEn entity,Integer shopId,String enterpriseCode, Long totalResults, String opType, String createUser,String interva,
			TradesOrderDao tradesOrderDao,TradesInfoDao tradesInfoDao,ShopStockDao shopStockDao,ProductService productService,PromotionDetailsDao promotionDetailsDao,
			SynLogDao synLogDao,ScheduleTimeDao scheduleTimeDao) {
		 this.updateTrade(entity, tradesOrderDao, tradesInfoDao, shopStockDao, productService, promotionDetailsDao,shopDao,channelDao);
		 this.updateSynLog(shopId, enterpriseCode, totalResults, opType, createUser, synLogDao,entity.getIsSuccess());
		 this.updateScheduleTime(shopId, totalResults,enterpriseCode, interva,scheduleTimeDao,entity);
	}
	
	private  void updateTrade(TmallOrderEn entity,TradesOrderDao tradesOrderDao,TradesInfoDao tradesInfoDao,ShopStockDao shopStockDao,
			                       ProductService productService,PromotionDetailsDao promotionDetailsDao,ShopDao shopDao, ChannelDao channelDao) {
		List<TradesInfo> tradesInfoList = entity.getTradesInfoList();
		List<TradesOrder> tradesOrderList =entity.getTradesOrderList();
		Map<String,List<PromotionDetails>> mapPromtion = entity.getMapPromtion();
		try {
			if(tradesInfoList != null){
				//获取组装店铺出库数据结构，即交易对应的订单行列表
				Map<String,List<TradesOrder>> mapOrder = entity.getMapOrder();
				//批量更新--插入交易信息记录
				for (TradesInfo tradesInfo : tradesInfoList) {
					//查询已有记录
					TradesInfo sysTradsInfo = tradesInfoDao.select(tradesInfo.getTid());
					if(sysTradsInfo != null){
						tradesInfo.setIs_Locked(sysTradsInfo.isIs_Locked());
						tradesInfo.setLocked(sysTradsInfo.getLocked());
						tradesInfo.setRemark(sysTradsInfo.getRemark());
						tradesInfo.setOfflineStatus(sysTradsInfo.getOfflineStatus());
						tradesInfo.setMergeStatus(sysTradsInfo.getMergeStatus());
						tradesInfo.setMergeTids(sysTradsInfo.getMergeTids());
						tradesInfo.setSplitStatus(sysTradsInfo.getSplitStatus());
						tradesInfo.setCompanyCode(sysTradsInfo.getCompanyCode());
						tradesInfo.setRefund(sysTradsInfo.isRefund());
						tradesInfo.setChangeGoods(sysTradsInfo.isChangeGoods());
						tradesInfo.setRefundGoods(sysTradsInfo.isRefundGoods());
						EnterpriseLogistics enLogistics = enterpriseLogisticDao.getDefaultLogistics(tradesInfo.getEnterpriseCode());
						if(enLogistics != null)
							tradesInfo.setCompanyCode(enLogistics.getCompanyCode());
						tradesInfoDao.update(tradesInfo);
					}else{
						//加上默认物流公司
						EnterpriseLogistics enLogistics = enterpriseLogisticDao.getDefaultLogistics(tradesInfo.getEnterpriseCode());
						if(enLogistics != null)
							tradesInfo.setCompanyCode(enLogistics.getCompanyCode());
						tradesInfo.setSplitStatus("INIT");
						tradesInfoDao.insert(tradesInfo);//插入交易信息表
						List<StockDetail> stockDetailList = new ArrayList<StockDetail>();
						List<TradesOrder> tradOrdList = mapOrder.get(tradesInfo.getTid());//交易对应的订单行
						if(tradOrdList != null){
							for (TradesOrder tradesOrder2 : tradOrdList) {
								//扣减库存 //根据skuId查询店铺仓库记录
								ShopStock  curShopStock = shopStockDao.getByShopIdSkuIdEpCode(Integer.valueOf(tradesOrder2.getOuterSkuId()), entity.getEnterpriseCode(), entity.getShopId());
								StockDetail stockDetail = new StockDetail();//生成店铺出库单明细对象
								if (curShopStock != null) {
									if(curShopStock.getStock() == 0){
										curShopStock.setStock(-tradesOrder2.getNum());//直接存负数
									}else{
										int subtract = curShopStock.getStock() - tradesOrder2.getNum();
									    curShopStock.setStock(subtract);
									}
									shopStockDao.update(curShopStock);//更新店铺仓库库存记录
									
									stockDetail.setPrice(curShopStock.getPrice());//把店铺仓库的价格赋值给出库单明细表中的价格字段
								}
								
								stockDetail.setSpuId(Integer.valueOf(tradesOrder2.getOuterIid()));
								stockDetail.setSkuId(Integer.valueOf(tradesOrder2.getOuterSkuId()));
								stockDetail.setIncoming(tradesOrder2.getNum());
								stockDetailList.add(stockDetail);
								//record_id,incoming,price,spu_id,fail_reason,fallback,sku_id,status
							}
						}
						
						//生成店铺出库单 //一个交易号对应多条明细    -----  一个库存单对应多条出库明细
						
						StockRecord  stockRecord = new StockRecord();
						stockRecord.setEnterpriseCode(entity.getEnterpriseCode());
						stockRecord.setStockType(StaticParam.STORE_OUT_OF_SALE);
						
						Shop shop = shopDao.get(entity.getShopId());
						if(shop != null){
							stockRecord.setOperateStoreId(shop.getShopId());
							stockRecord.setRelevantStoreId(StaticParam.VIRTUAL_WAREHOUSE);
							Channel channel = channelDao.getChannelByChannelCode(shop.getChannelCode());
							if(channel != null){
								stockRecord.setChannelCode(channel.getChannelCode());
								stockRecord.setRelevantChannelCode(channel.getChannelCode());
								stockRecord.setOperateChannelCode(channel.getChannelCode());
							}
						}
						
						stockRecord.setRecordType(StaticParam.D_STOCK_TYPE_OUT);
						stockRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
						stockRecord.setCreateUserId(1);//adminId
						stockRecord.setRelevantInfo(tradesInfo.getTid());//交易号
						stockRecord.setStockDetailList(stockDetailList);//出库明细记录
						//插入出库主表以及明细表
						productService.insertStockRecord(stockRecord, StaticParam.OUT_FLAG);
					}
					//删除优惠信息
					promotionDetailsDao.delteByTid(tradesInfo.getTid());
					List<PromotionDetails> promList = mapPromtion.get(tradesInfo.getTid());
					if(promList != null)
						promotionDetailsDao.insert(promList);//插入优惠信息
				}
				
				//批量插入订单行信息记录
				for (TradesOrder tradesOrder : tradesOrderList) {
					//通过oid查询已有的交易订单行
					TradesOrder sysTradesOrder = tradesOrderDao.getTradesOrder(tradesOrder);
					if(sysTradesOrder != null){
						tradesOrder.setOrderId(sysTradesOrder.getOrderId());
						tradesOrder.setConsignTime(sysTradesOrder.getConsignTime());
						tradesOrder.setSplitNum(sysTradesOrder.getSplitNum());
						tradesOrderDao.update(tradesOrder);
					}else{
						//插入数据
						tradesOrder.setIsAfterSale(0);
						tradesOrderDao.insert(tradesOrder);
					}
				}
				
			}
		} catch (Exception e) {
			logger.error("交易信息数据更新出错:"+e.getMessage(),e);
		}
	}
	
	private  void updateSynLog(Integer shopId,String enterpriseCode,Long totalResults,String opType,String createUser,SynLogDao synLogDao,boolean isSuccess){
		SynLog synLog = new SynLog();
		synLog.setShopId(shopId);
		synLog.setEnterpriseCode(enterpriseCode);
		synLog.setOpType(opType);
		synLog.setDataType(SynType.ORDER_SYNCHRONIZATION.name());
		if(totalResults != null && totalResults > 0){
			synLog.setNum(Integer.valueOf(totalResults.toString()));
		}else{
			synLog.setNum(0);
		}
		synLog.setIsSuccess(isSuccess);
		synLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
		synLog.setCreateUser(createUser);//adminId
		synLogDao.insert(synLog);
	}
	
	private  void updateScheduleTime(Integer shopId,Long totalResults,String enterpriseCode,String interva,ScheduleTimeDao scheduleTimeDao,TmallOrderEn entity){
    	//根据    企业编码，店铺ID，调度组 查询当前记录，如有更新，没有插入数据
		try {
			ScheduleTime scheduleTimeDto = new ScheduleTime();
//			List<TradesInfo> tradesInfoList = this.compareModifiedTime(entity.getTradesInfoList());
			
			if(!StringUtils.isEmpty(shopId.toString())){
				scheduleTimeDto.setShopId(shopId);
			}
			scheduleTimeDto.setBusinessGroup("order");
	    	ScheduleTime  scheduleTime = scheduleTimeDao.getScheduleTime(scheduleTimeDto);
	    	
	    	if(scheduleTime != null){
	    		//调度任务上一次更新时间加上调度任务间隔时间
	    		//大于30  按29算
	    		Integer intervaI = Integer.valueOf(interva);
	    		if(intervaI >=30){
	    			scheduleTime.setLastSynTime(SueCloudDateUtil.getEndTime(scheduleTime.getLastSynTime(),29));
	    		}else{
	    			scheduleTime.setLastSynTime(SueCloudDateUtil.getEndTime(scheduleTime.getLastSynTime(),intervaI));
	    		}
	    		scheduleTimeDao.update(scheduleTime);
	    	}else{
	    		scheduleTime = new ScheduleTime();
	    		scheduleTime.setShopId(shopId);
	    		scheduleTime.setEnterpriseCode(enterpriseCode);
	    		scheduleTime.setBusinessGroup("order");
	    		scheduleTime.setConfigType("synOrder");
	    		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    		String dateStr = sdf.format(new Date());
	    		Date date = sdf.parse(dateStr);
	    		scheduleTime.setLastSynTime(date);
	    		scheduleTimeDao.insert(scheduleTime);
	    	}
	    	
//	    	if(totalResults != null && totalResults > 0){
//	    		if(scheduleTime != null){
//	    			scheduleTime.setLastSynTime(tradesInfoList.get(0).getModified());
//		    		scheduleTimeDao.update(scheduleTime);
//	    		}else{
//	    			scheduleTime = new ScheduleTime();
//		    		scheduleTime.setShopId(shopId);
//		    		scheduleTime.setEnterpriseCode(enterpriseCode);
//		    		scheduleTime.setBusinessGroup("order");
//		    		scheduleTime.setConfigType("synOrder");
//		    		scheduleTime.setLastSynTime(tradesInfoList.get(0).getModified());
//		    		scheduleTimeDao.insert(scheduleTime);
//	    		}
//	    	}
		} catch (Exception e) {
			logger.error("更新同步时间表记录出错："+e.getMessage(),e);
		}
	}

	@SuppressWarnings("unused")
	private List<TradesInfo> compareModifiedTime(List<TradesInfo> tradesInfoList){
		if(tradesInfoList != null){
			Collections.sort(tradesInfoList, new Comparator<TradesInfo>() {
				@Override
				public int compare(TradesInfo o1, TradesInfo o2) {
					Date dateOne =  o1.getModified();
					Date dateTwo =  o2.getModified();
					return dateTwo.compareTo(dateOne);
				}
			});
			
			return tradesInfoList;
		}else{
			return null;
		}
	}


}
